package com.example.ee_demo.controller;

import org.apache.tomcat.util.http.parser.HttpParser;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

/**
 * @className: CookieController
 * @author: 芃
 * @description: Cookie & Session
 * @date: 2024/12/20 15:32
 */
@RestController
@RequestMapping("/session")
public class SessionController {
    private static final String token = "USER_TOKEN";
    private static final String token2 = "USER_TOKEN2";
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookie = request.getCookies();
        for (int i = 0; i < cookie.length; i++) {
            System.out.println(cookie[i].getName() + ":" + cookie[i].getValue());
        }
        return "获取Cookie";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("zyp")String cookie){
        return "获取Cookie:"+cookie;
    }




    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request, @RequestParam String userName,@RequestParam String password){
        HttpSession session = request.getSession();
        session.setAttribute(token,userName);
        session.setAttribute(token2,password);
        return "session存储成功";
    }



    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        //从cookie中获取到了sessionID，根据sessionID获取到session对象,如果没有获取到，则会创还能一个session对象
        HttpSession session = request.getSession();
        String sessionID = session.getId();
        System.out.println(sessionID);
        Object object = session.getAttribute(token);
        return object.toString();
    }



    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        System.out.println(session.getId());
        Object object = session.getAttribute(token);
        return object.toString();
    }


    @RequestMapping("/getSession3")
    public String getSession2(@SessionAttribute(token)String name){
        return name;
    }
}
